﻿using System;
using System.Drawing;
using System.Windows.Forms;
using CppProject;

namespace BackEndProcessorInterface
{
    public partial class TopForm : Form
    {
        private readonly CppController cppController;
        private readonly MainMenu menu;
        private readonly ConsoleForm centerForm;
        private readonly ToolBarPanel toolForm;
        private static Point locationPoint;
        private const string onBorderTextTool = "Выключить";
        private const string offBorderTextTool = "Включить";

        public TopForm()
        {
            InitializeComponent();
                        
            cppController = new CppController();
            menu = new MainMenu(this, cppController);
            
            centerForm = new ConsoleForm(cppController);
            toolForm = new ToolBarPanel(menu, cppController);
            
            centerForm.Owner = this;
            toolForm.Owner = this;
        }
        
        public string IsoLinesToString() { return toolForm.IsolinesToString(); }
        public void IsoLinesFromString(string s) { toolForm.IsolinesFromString(s); }
        public string ColorScaleToString() { return toolForm.ColorScaleToString(); }
        public void ColorScaleFromString(string s) { toolForm.ColorScaleFromString(s);  }

        public void ViewButton(String name, bool val)
        {
            switch (name)
            {
                case "toolStripButtonPanelLog":
                    toolStripButtonPanelLog.Checked = val;
                    break;
                case "toolStripButtonPanelRight":
                    toolStripButtonPanelRight.Checked = val;
                    break;
                case  "toolStripButtonBorderEnable":
                    toolStripButtonBorderEnable.Checked = val;
                    break;
                case "toolStripButtonMostTop":
                    toolStripButtonMostTop.Checked = val;
                    break;
            }
        }
        public void PaintMouseFlag(bool val)
        {
            centerForm.PaintMouseFlag = val;
        }

        public void AddFlag()
        {
            toolForm.AddFlag();
        }
        public void RemoveFlags()
        {
            toolForm.RemoveFlags();
        }
        public void MousePointerButton(String name, bool val)
        {
            toolForm.SetMousePointer(name, val);
            var mflag = false;
            switch (name)
            {
                case "toolStripButtonMouseDefault":
                   if(!val) mflag = true;                    
                    break;
                case "toolStripButtonFlag":
                    if (val) mflag = true; 
                    break;
            }
            PaintMouseFlag(mflag);
            SetText(String.Format("Chooser : {0} is {1}", name, val));
        }
        public  PConfig GetGraphicsConfig
        {
            get { return toolForm.GetGraphicsConfig(); }

        }
        public PConfig GetPanelConfig
        {
            get
            {
                var panel = new PConfig
                                {
                                    {"ToolPanel", toolStripButtonPanelRight.Checked},
                                    {"Console", toolStripButtonPanelLog.Checked}
                                };
                panel.Name = "Panels";
                return panel;
            }
        }
        public void SetGraphicsSetting(String name, bool val)
        {
            toolForm.SetControlState(name, val);
            switch (name)
            {
                case "checkBoxAxis":
                    centerForm.PaintAxis = val;
                    break;
                case "checkBoxMesh":
                    centerForm.PaintMesh = val;
                    break;
                case "checkBoxMeshFI":
                    centerForm.PaintMeshFi = val;
                    break;
                case "checkBoxIsoline":
                    centerForm.PaintIsoline = val;
                    break;
                case "checkBoxFlags":
                    centerForm.PaintFlags = val;
                    break;
            }
        }
        public  void SetTask(string taskMessage)
        {
                centerForm.SetTask(taskMessage);
        }

        public void SetText(String date, String textMessage)
        {
            SetText(String.Format("[{0}]: {1}", date, textMessage));            
        }
        public void _BorderVisible(bool val)
        {
            centerForm._BorderVisible(val);
            toolForm._BorderVisible(val);            
        }
        public void ScaleGrad(string name)
        {
            toolForm.ScaleGrad(name);
        }
        private void TopForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show(this, "Хотите выйти?", "Выход", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.No)
                {
                    e.Cancel = true;
                    toolForm.Show();
                }
            if(result == DialogResult.Yes)
                {
                    e.Cancel = false;
                    centerForm.CLOSE = true;              
                    toolForm.CLOSE = true;             
                }
        }
        private void ChangeLocationAdditionalForms()
        {
            var x = Location.X - locationPoint.X;
            var y = Location.Y - locationPoint.Y;
            
            centerForm.Location = new Point(centerForm.Location.X + x, centerForm.Location.Y + y);
            toolForm.Location = new Point(toolForm.Location.X + x, toolForm.Location.Y + y);
            locationPoint = Location;
        }
        private  void LoadDefaultFiles()
        {
            var path = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
            path = path != null ? path.Substring(0, path.LastIndexOf("\\")) : "";
            var filename = "dsettings.xml";
            var directory = string.Format("{0}{1}", path, "\\default\\");
            var filepath = System.IO.Path.Combine(directory, filename);
            if (!System.IO.File.Exists(filepath))
            {
                try
                {
                    System.IO.Directory.CreateDirectory(directory);
                    var subpath = path != null ? path.Substring(0, path.LastIndexOf("\\")) : "";
                    System.IO.File.Copy(string.Format("{0}{1}", subpath, "\\default\\dsettings.xml"), filepath);
                }
                catch (System.IO.IOException ioe)
                {
                    ShowErrorBox(ioe.Message);
                }
            }

            /*#if(DEBUG)
                        path = path != null ? path.Substring(0, path.LastIndexOf("\\") ) : "";
            #endif
             */

            if (!menu.LoadInterfaceSettings(filepath))
                ShowErrorBox("Can't load default settings!");
        }

        private void TopForm_Load(object sender, EventArgs e)
        {
            LoadDefaultFiles();

            if (menu != null)
            {
                centerForm.SetLeftContextMenu = menu.CreateLeftContextMenu();
                centerForm.SetRightContextMenu = menu.CreateRithtContextMenu();
            }

            var screenwidth = SystemInformation.PrimaryMonitorSize.Width;
            var screenheight = SystemInformation.PrimaryMonitorSize.Height;
            MaximumSize = new Size(screenwidth*4/5,Size.Height);
            MinimumSize = new Size(Width,Height);
            var userwidth = Size.Width + toolForm.Width;
            var userheight = Size.Height + centerForm.Height;
            Location  = new Point((screenwidth - userwidth)/2,(screenheight - userheight)/2);
            centerForm.Location = new Point(Location.X, Location.Y + 130);
            toolForm.Location = new Point(Location.X + 580, Location.Y);
            locationPoint = Location;

            if(toolStripButtonPanelLog.Checked)
            centerForm.Show();
            if(toolStripButtonPanelRight.Checked)
            toolForm.Show();
        }
        private void TopForm_Move(object sender, EventArgs e)
        {
            switch (WindowState)
            {
                case FormWindowState.Minimized:
                    toolForm.WindowState = FormWindowState.Minimized;
                    centerForm.WindowState = FormWindowState.Minimized;
                    break;
                case FormWindowState.Normal:
                    try
                    {
                        if (FormWindowState.Minimized == toolForm.WindowState)
                            toolForm.WindowState = FormWindowState.Normal;
                        if (centerForm.WindowState == FormWindowState.Minimized)
                            centerForm.WindowState = FormWindowState.Normal;
                    }
                    catch (NullReferenceException nre)
                    {
                        ShowErrorBox(nre.Message);
                    }
                    
                    ChangeLocationAdditionalForms();
                    break;
            }
          
        }       
        private void toolStripButton_CheckStateChanged(object sender, EventArgs e)
        {
            var item = 0;
            var view = false;
            
            try
            {
                string tooltiptext;
                var check = ((ToolStripButton) sender).Checked;
                switch (((ToolStripButton)sender).Name)
                {
                    case "toolStripButtonPanelRight":
                        item = 1;
                        if (check)
                        {
                            tooltiptext = string.Format("{0} {1}", onBorderTextTool,toolStripButtonPanelRight.Text);
                            toolForm.Show();
                            view = true;
                        }
                        else
                        {
                             tooltiptext = string.Format("{0} {1}", offBorderTextTool, toolStripButtonPanelRight.Text);
                            
                            toolForm.Hide();
                        }
                        toolStripButtonPanelRight.ToolTipText = tooltiptext;
                        break;
                    case "toolStripButtonPanelLog":
                        if (check)
                        {
                            tooltiptext = string.Format("{0} {1}", onBorderTextTool, toolStripButtonPanelLog.Text);
                            centerForm.Show();
                            view = true;
                        }
                        else
                        {
                            tooltiptext = string.Format("{0} {1}", offBorderTextTool, toolStripButtonPanelLog.Text);
                            centerForm.Hide();
                        }
                        toolStripButtonPanelLog.ToolTipText = tooltiptext;
                        break;
                    case "toolStripButtonBorderEnable":
                        tooltiptext = check ? string.Format("{0} {1}", offBorderTextTool, toolStripButtonBorderEnable.Text) :
                            string.Format("{0} {1}", onBorderTextTool, toolStripButtonBorderEnable.Text);
                        _BorderVisible(check);
                        toolStripButtonBorderEnable.ToolTipText = tooltiptext;
                        break;
                    case "toolStripButtonMostTop":
                        tooltiptext = check ? string.Format("{0} {1}", onBorderTextTool, toolStripButtonMostTop.Text) : 
                            string.Format("{0} {1}", offBorderTextTool, toolStripButtonMostTop.Text);
                        TopMost = check;
                        toolStripButtonMostTop.ToolTipText = tooltiptext;
                        break;
                }
            }
            catch (ObjectDisposedException ode)
            {
                ((ToolStripButton)sender).Checked = false;
                ShowErrorBox(ode.Message);              
            }
            finally
            {
                menu.ViewSettings(item, view);
            }
        }
        public void ShowErrorBox(String message)
        {
            MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        private void SetText(String message)
        {
            centerForm.SetText(message);
        }

        private void toolStripButtonShutdown_Click(object sender, EventArgs e)
        {
            Close();
        }

      
        
        
    }
}
